package api;

import appmodel.JsonModel;
import common.StringUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import service.UserService;

@Controller
@RequestMapping({ "/upload" })
public class UpLoadFileController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = { "imge" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public JSONObject index(HttpServletRequest request, JsonModel jsonModel,
			HttpServletResponse response,
			MultipartFile imge) {
		
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
		response.addHeader("Access-Control-Max-Age", "7200");// 120 min
		
		String image = StringUtil.uploadOnlyFile(request, imge);

		if (!StringUtil.isEmpty(image)) {
			jsonModel.setSuccess(true);
			jsonModel.setMsg("上传成功");
			jsonModel.setjData(image);
			jsonModel.setToken("");
		} else {
			jsonModel.setSuccess(false);
			jsonModel.setMsg("上传失败");
			jsonModel.setjData("");
			jsonModel.setToken("");
		}

		return JSONObject.fromObject(jsonModel);
	}
}